package com.vnp.vchat.util;

import java.io.File;
import java.io.IOException;

import android.R.color;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.telpoo.frame.delegate.Idelegate;
import com.vnp.vchat.R;

public class MyDialog extends Activity implements OnClickListener {
	private final String VCHAT = "vChat";

	private MediaRecorder recorder = null;
	private int currentFormat = 0;
	private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.OutputFormat.THREE_GPP };
	private long startTime = 0L;
	private Handler myHandler = new Handler();
	long timeInMillies = 0L;
	long timeSwap = 0L;
	long finalTime = 0L;
	TextView tv_time, tvCancel;
	TextView tv_sound;
	LinearLayout ll_resize;
	boolean isRecording = false;
	Handler mHandler = new Handler();
	Boolean recording;
	String fileName;
	ImageView btnstart;
	ImageView ivLock, ivCancel;
	float pointerX, pointerY;
	View ivLockF, ivCancelF, cent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.voice_call);
		currentFormat = 0;

		startTime = 0L;
		myHandler = new Handler();
		timeInMillies = 0L;
		timeSwap = 0L;
		finalTime = 0L;
		mHandler = new Handler();

		fileName = getFilename1();

		btnstart = (ImageView) findViewById(R.id.btnStart);
		tv_time = (TextView) findViewById(R.id.time_goi_thoai);
		tv_sound = (TextView) findViewById(R.id.tv_sound);
		ll_resize = (LinearLayout) findViewById(R.id.ll_sezire);
		tvCancel = (TextView) findViewById(R.id.tvCancel);
		ivCancel = (ImageView) findViewById(R.id.ivCancel);
		ivLock = (ImageView) findViewById(R.id.ivLock);
		ivLockF = (ImageView) findViewById(R.id.ivLockF);
		ivCancelF = (ImageView) findViewById(R.id.ivCancelF);
		cent = (View) findViewById(R.id.cent);
		ivCancel.setOnClickListener(this);
		ivLock.setOnClickListener(this);
		findViewById(R.id.root1).setOnTouchListener(new OnTouchListener() {

			private boolean isHoldingFist;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				pointerX = event.getX();
				pointerY = event.getY();
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (isInView(btnstart)) {
						if (!isRecording) {
							isHoldingFist = true;
							startRecording();
						} else
							stopRecording(true);
					} else {
						// if(!isRecording)
						// stopRecording(false);
						if (isInView(ivLockF)) {
							stopRecording(isRecording);
						}
						if (isInView(ivCancelF))
							stopRecording(false);
					}

					break;

				case MotionEvent.ACTION_MOVE:
					if (isHoldingFist) {
						if (isInView(ivLockF)) {
							ivLock.setImageResource(R.drawable.voice_fh_hold);
						} else
							ivLock.setImageResource(R.drawable.voice_fh_unlock);

						if (isInView(cent)) {
							tv_time.setTextColor(Color.parseColor("#D50000"));
							tvCancel.setText("Thả ra để hủy");
						} else {
							tvCancel.setText("Kéo vào đây để hủy");
							tv_time.setTextColor(Color.parseColor("#ffffff"));
						}
					}

					break;

				case MotionEvent.ACTION_UP:
					isHoldingFist = false;
					if (isInView(ivLockF)) {
						ivLock.setVisibility(View.VISIBLE);
						ivLock.setImageResource(R.drawable.stencils_ic_timedongy);
						ivCancel.setVisibility(View.VISIBLE);
						ivCancel.setImageResource(R.drawable.stencils_ic_timehuy);
					}

					if (isInView(cent)) {
						stopRecording(false);
					} else
						cent.setVisibility(View.VISIBLE);

					if (!isInView(btnstart) && !isInView(ivLockF) && !isInView(cent)) {
						stopRecording(true);
					}
					if (isInView(btnstart))
						stopRecording(true);

					break;

				default:
					break;
				}
				return true;
			}
		});

		getWindow().setBackgroundDrawable(new ColorDrawable(0));
		getWindow().setGravity(Gravity.CENTER);

	}

	@Override
	protected void onStop() {
		super.onStop();
		if (isRecording)
			stopRecording(false);
	}

	protected boolean isInView(View v) {
		if (pointerX > v.getLeft() && pointerX < v.getRight() && pointerY > v.getTop() && pointerY < v.getBottom())
			return true;
		return false;
	}

	private Runnable updatelever = new Runnable() {

		@SuppressLint("ResourceAsColor")
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				int lever = recorder.getMaxAmplitude() / 100;
				mHandler.postDelayed(this, 500);
				ResizeAnimation resizeAnimation = new ResizeAnimation(ll_resize, lever);
				resizeAnimation.setDuration(500);

				ll_resize.startAnimation(resizeAnimation);
				// ll_resize.setBackgroundColor(R.color.xam_nhat);
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
	};
	private Runnable updateTimerMethod = new Runnable() {

		@Override
		public void run() {
			timeInMillies = SystemClock.uptimeMillis() - startTime;
			finalTime = timeSwap + timeInMillies;

			int seconds = (int) (finalTime / 1000);
			int minutes = seconds / 60;
			seconds = seconds % 60;
			int milliseconds = (int) (finalTime % 1000);
			tv_time.setText("" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
			myHandler.postDelayed(this, 0);
		}

	};

	private String getFilename1() {
		String filepath = Environment.getExternalStorageDirectory().getPath();
		File file = new File(filepath, VCHAT);

		if (!file.exists()) {
			file.mkdirs();
		}

		return (file.getAbsolutePath() + "/" + System.currentTimeMillis() / 1000 + ".mp3");
	}

	private void startRecording() {

		ivLock.setVisibility(View.VISIBLE);
		ivCancel.setVisibility(View.GONE);
		btnstart.setImageResource(R.drawable.btn_voice_o);
		cent.setVisibility(View.VISIBLE);

		startTime = SystemClock.uptimeMillis();
		myHandler.postDelayed(updateTimerMethod, 1000);
		myHandler.postDelayed(updatelever, 0);
		isRecording = true;

		recorder = new MediaRecorder();
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setOutputFormat(output_formats[currentFormat]);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		recorder.setOutputFile(fileName);
		recorder.setOnErrorListener(errorListener);
		recorder.setOnInfoListener(infoListener);
		try {

			recorder.prepare();
			recorder.start();

		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void stopRecording(boolean isSave) {
		timeSwap += timeInMillies;
		myHandler.removeCallbacks(updateTimerMethod);
		mHandler.removeCallbacks(updatelever);
		isRecording = false;

		if (null != recorder) {
			recorder.stop();
			recorder.reset();
			recorder.release();
			recorder = null;

		}

		Intent it = new Intent();
		it.putExtra("mpString", fileName);
		if (!isSave) {

			setResult(RESULT_CANCELED, it);
		} else
			setResult(RESULT_OK, it);
		finish();
	}

	private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
		@Override
		public void onError(MediaRecorder mr, int what, int extra) {
			// Toast.makeText(ChatNewActivity.this,
			// "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
		}
	};

	private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
		@Override
		public void onInfo(MediaRecorder mr, int what, int extra) {
			// Toast.makeText(ChatNewActivity.this,
			// "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
			// .show();
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ivLock:
			stopRecording(true);
			break;

		default:
			break;
		}
	}

}
